import { ref, computed } from 'vue'
import { generateMaze } from '@/utils/mazeGenerator'

const columns = ref(15)
const rows = ref(15)

// 迷宫布局 (0=可通过, 1=障碍)
const maze = ref([])

// 游戏状态
const gameState = ref('ready') // 'ready', 'playing', 'paused', 'completed'

// 初始化迷宫
const initMaze = () => {
    try {
        maze.value = generateMaze(rows.value, columns.value)
        gameState.value = 'ready'
    } catch (error) {
        console.error('迷宫生成失败:', error)
        // 生成一个简单的默认迷宫
        maze.value = Array(rows.value).fill().map(() => Array(columns.value).fill(0))
        maze.value[1][1] = 0
        maze.value[rows.value-2][columns.value-2] = 0
        console.log('使用默认迷宫:', maze.value)
    }
}

// 重新生成迷宫
const regenerateMaze = () => {
    initMaze()
}

// 改变迷宫大小
const changeMazeSize = (newRows, newCols) => {
    rows.value = newRows
    columns.value = newCols
    regenerateMaze()
}

// 计算迷宫信息
const mazeInfo = computed(() => {
    if (!maze.value || maze.value.length === 0) {
        return {
            totalCells: 0,
            wallCells: 0,
            pathCells: 0,
            wallPercentage: 0
        }
    }
    
    const totalCells = rows.value * columns.value
    const wallCells = maze.value.flat().filter(cell => cell === 1).length
    const pathCells = totalCells - wallCells
    
    return {
        totalCells,
        wallCells,
        pathCells,
        wallPercentage: Math.round((wallCells / totalCells) * 100)
    }
})

// 检查位置是否有效（可通过）
const isValidPosition = (row, col) => {


    return row >= 0 && row < rows.value && 
           col >= 0 && col < columns.value && 
           maze.value[row] && maze.value[row][col] === 0
}

// 获取相邻的有效位置
const getValidNeighbors = (row, col) => {
    const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]] // 上下左右
    const neighbors = []
    
    for (const [dr, dc] of directions) {
        const newRow = row + dr
        const newCol = col + dc
        if (isValidPosition(newRow, newCol)) {
            neighbors.push([newRow, newCol])
        }
    }
    
    return neighbors
}

// 生成随机可通过位置
const generateRandomValidPosition = () => {
    const maxAttempts = 100 // 防止无限循环
    let attempts = 0
    
    while (attempts < maxAttempts) {
        const row = Math.floor(Math.random() * rows.value)
        const col = Math.floor(Math.random() * columns.value)
        
        if (isValidPosition(row, col)) {
            return { row, col }
        }
        attempts++
    }
    
    // 如果随机生成失败，返回第一个有效位置
    for (let row = 0; row < rows.value; row++) {
        for (let col = 0; col < columns.value; col++) {
            if (isValidPosition(row, col)) {
                return { row, col }
            }
        }
    }
    
    // 如果都没有，返回边界位置
    return { row: 0, col: 0 }
}

// 生成多个不重复的随机位置
const generateMultipleValidPositions = (count) => {
    const positions = []
    const usedPositions = new Set()
    
    console.log('=== 生成猫咪位置调试信息 ===')
    console.log('请求生成位置数量:', count)
    console.log('迷宫数据:', maze.value)
    console.log('迷宫是否为空:', !maze.value || maze.value.length === 0)
    console.log('迷宫行数:', maze.value ? maze.value.length : 0)
    console.log('迷宫列数:', maze.value && maze.value[0] ? maze.value[0].length : 0)
    
    if (!maze.value || maze.value.length === 0) {
        console.error('迷宫数据为空，无法生成猫咪位置')
        return positions
    }
    
    for (let i = 0; i < count; i++) {
        let position
        let attempts = 0
        const maxAttempts = 50
        
        do {
            position = generateRandomValidPosition()
            attempts++
        } while (usedPositions.has(`${position.row},${position.col}`) && attempts < maxAttempts)
        
        if (attempts < maxAttempts) {
            positions.push(position)
            usedPositions.add(`${position.row},${position.col}`)
        }
    }
    
    return positions
}

// 检查位置是否在边界
const isBoundaryPosition = (row, col) => {
    return row === 0 || row === rows.value - 1 || 
           col === 0 || col === columns.value - 1
}

// 获取所有可通过的位置
const getAllValidPositions = () => {
    const positions = []
    for (let row = 0; row < rows.value; row++) {
        for (let col = 0; col < columns.value; col++) {
            if (isValidPosition(row, col)) {
                positions.push({ row, col })
            }
        }
    }
    return positions
}


export default { 
    maze,
    columns,
    rows,
    gameState,
    mazeInfo,
    initMaze,
    regenerateMaze,
    changeMazeSize,
    isValidPosition,
    getValidNeighbors,
    generateRandomValidPosition,
    generateMultipleValidPositions,
    isBoundaryPosition,
    getAllValidPositions
}

